package Simulator;

import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Image;
import java.util.HashMap;

import javax.swing.JPanel;

@SuppressWarnings("serial")
public class FieldView extends JPanel {
	private final int GRID_VIEW_SCALING_FACTOR = 10;
	private static final Color UNKNOWN_COLOR = Color.gray;
	@SuppressWarnings("rawtypes")
	private HashMap<Class, Color> colors;
	private int gridWidth, gridHeight;
	private int xScale, yScale;
	Dimension size;
	private Graphics g;
	private Image fieldImage;

	@SuppressWarnings("rawtypes")
	public FieldView(int height, int width) {
		setSize(height, width);
		colors = new HashMap<Class, Color>();
	}

	public void setSize(int height, int width) {
		gridHeight = height;
		gridWidth = width;
		size = new Dimension(0, 0);
	}

	@SuppressWarnings("rawtypes")
	public void setColor(Class actorClass, Color color) {
		colors.put(actorClass, color);
	}

	@SuppressWarnings("rawtypes")
	public Color getColor(Class actorClass) {
		Color col = colors.get(actorClass);
		if (col == null) {
			return UNKNOWN_COLOR;
		} else {
			return col;
		}
	}

	public Dimension getPreferredSize() {
		return new Dimension(gridWidth * GRID_VIEW_SCALING_FACTOR, gridHeight
				* GRID_VIEW_SCALING_FACTOR);
	}

	public void preparePaint() {
		if (!size.equals(getSize())) {
			size = getSize();
			fieldImage = createImage(size.width, size.height);
			g = fieldImage.getGraphics();

			xScale = size.width / gridWidth;
			if (xScale < 1) {
				xScale = GRID_VIEW_SCALING_FACTOR;
			}
			yScale = size.height / gridHeight;
			if (yScale < 1) {
				yScale = GRID_VIEW_SCALING_FACTOR;
			}
		}
	}

	public void drawMark(int x, int y, Color color) {
		g.setColor(color);
		g.fillRect(x * xScale, y * yScale, xScale - 1, yScale - 1);
	}

	public void fillRect(int x, int y, Color color) {
		g.setColor(color);
		g.fillRect(x, y, 5, 5);
	}

	public void clearRect(int x) {
		g.clearRect(x, 0, 5, 300);
	}

	public void fillArc(int start, int stop, Color color) {
		g.setColor(color);
		g.fillArc(50, 100, 200, 100, start, stop);
	}

	public void paintComponent(Graphics g) {
		if (fieldImage != null) {
			Dimension currentSize = getSize();
			if (size.equals(currentSize)) {
				g.drawImage(fieldImage, 0, 0, null);
			} else {
				g.drawImage(fieldImage, 0, 0, currentSize.width,
						currentSize.height, null);
			}
		}
	}
}